package com.cxy.usercenter.service.user;

import com.cxy.usercenter.dao.bonusEventLog.BonusEventLogMapper;
import com.cxy.usercenter.dao.user.UserMapper;
import com.cxy.usercenter.domain.dto.messaging.UserAddBonusMsgDTO;
import com.cxy.usercenter.domain.dto.user.UserLoginDTO;
import com.cxy.usercenter.domain.entity.bonusEventLog.BonusEventLog;
import com.cxy.usercenter.domain.entity.user.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author: huayushu luming
 * @date: 2020-11-26 00:39
 * @desc:
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {

    private final UserMapper userMapper;
    private final BonusEventLogMapper bonusEventLogMapper;


    public User findById(Integer id){
        return this.userMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addBonus(UserAddBonusMsgDTO message) {
        //收到消息的时候，执行业务
        //1.为用户加积分
        Integer userId = message.getUserId();
        Integer bonus = message.getBonus();
        User user = this.userMapper.selectByPrimaryKey(userId);
        user.setBonus(user.getBonus()+bonus);
        this.userMapper.updateByPrimaryKeySelective(user);

        //2.记录日志到bonus_event_log表里面
        this.bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(userId)
                        .value(bonus)
                        .event("CONTRIBUTE")
                        .createTime(new Date())
                        .description("投稿加积分")
                        .build());
        log.info("积分添加完毕!");
    }

    public User login(UserLoginDTO loginDTO, String openid) {
        User user = this.userMapper.selectOne(
                User.builder()
                        .wxId(openid)
                        .build()
        );
        if (user == null) {
            User userToSave = User.builder()
                    .wxId(openid)
                    .bonus(300)
                    .wxNickname(loginDTO.getWxNickname())
                    .avatarUrl(loginDTO.getAvatarUrl())
                    .roles("user")
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            this.userMapper.insertSelective(
                    userToSave
            );
            return userToSave;
        }
        return user;
    }
}
